// packageCommunity/pages/releaseImg/index.js
import{comments} from "../../../js/modules/mall.js" 
import {
  upload
} from '../../../js/modules/material.js'
import { 
  util,api
} from '../../../js/util';

var app = getApp();
const pageBehavior = require('../../../js/common/PageBehavior')
import authorize from '../../../js/modules/authorize'

Page({
  behaviors: [pageBehavior],
  /**
   * 页面的初始数据
   */
  data: {
    imgDomain:api.imgDomain,
    uploadImageList:[], // 添加图片列表
    virtualImageList:[],
    currentNum:0, //输入多少字
    readerValue:'', //textarea值
    uploadShopList:[],//添加商品列表
    shopImageList:[],
    // Title:'',//标题
    type:1,//帖子类型
    SectionId:'',//板块id
    SectionName:'',//板块Name
    goodsList:[],//添加商品
    postId:'',//帖子id
    PostDetail:{},//帖子详情
    navList:[],//发布板块
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (!authorize.isLogin('store')) {
      authorize.redirect('store')
      return
    }
    this.setData({
      type:options.type,
      postId:Number(options.postid)
    })
    this.navDataList();
    if(options.postid){
      this.navDataList();
      this.getDelPostDetail();
    }
  },
  /**
  * 获取已删除帖子详情
  */
  getDelPostDetail:function(){
    var that = this;
    // this.data.postId--118
    var data = {Id:this.data.postId};
    comments.getDelPostDetail(data,function(content){
      if(content.Success){
        // console.log(content,'----已删除帖子详情');
        var data = content.Content;
        var name = '';
        var navList = that.data.navList;
        for(i=0;i<navList.length;i++){
          if(data.SectionId == navList[i].Id){
            name = navList[i].Name;
          }
        }
        if(data.ImageList[0].indexOf(',') === -1){
          data.ImageList = data.ImageList;
        }else{
          data.ImageList = data.ImageList[0].split(',');
        }
        var imgList = data.ImageList;
        for(var i = 0;i<imgList.length;i++){
          imgList[i] = that.data.imgDomain+imgList[i];
        }
        // console.log(imgList,'----item',that.data.imgDomain);
        var list = [];
        data.Products.forEach(function(item){
          list.push({
            SaleValue:item.ProductId,
            image:that.data.imgDomain+item.DefaultPic
          })
        })
        that.setData({
          uploadImageList:imgList,
          virtualImageList:data.ImageList,
          uploadShopList:list,
          Title:data.Title,
          readerValue:data.Content,
          SectionId:data.SectionId, 
          SectionName:name
        })
        // console.log(imgList,'===imgList==',that.data.uploadImageList);
      }else{
        util.alert(content.Message);
      }
    })
  },
   /**
   * 添加图片
   */
  bindUploadEvent:function(e){
    // var idx = e.currentTarget.dataset.idx;
    var that = this;
    if (this.data.uploadImageList.length >= 9) {
      util.tips("最多只能上传9张");
      return;
    }
    var count = 9 - that.data.uploadImageList.length;
    let uploadImageList = that.data.uploadImageList
    let virtualImageList = that.data.virtualImageList
    wx.chooseImage({
      count: count,
      sizeType: ['compressed'],
      sourceType: ['album'],
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        // console.log("chooseImage res====", res.tempFilePaths)
        var tempFilePaths = res.tempFilePaths;
        var data = {num:1011,type:1,tempFilePaths:tempFilePaths};
        upload.upload_image_server(data, function (image_list) {
          if (image_list.length==0){
            util.alert("上传失败");
            return;
          }
          let upList = []
          let viList = []
          upList = [...uploadImageList, ...tempFilePaths]
          viList = [...virtualImageList, ...image_list]
          that.setData({
            uploadImageList: upList,
            virtualImageList: viList
          })
        })

      }
    });
  },
  /**
   * 删除--添加图片
   */
  onDelImageEvent:function(e){
    var that = this;
    var imgidx = e.currentTarget.dataset.imgidx;
    var image_list = that.data.uploadImageList;
    image_list.splice(imgidx, 1);
    var virtual_list = that.data.virtualImageList;
    virtual_list.splice(imgidx, 1);
    that.setData({
      uploadImageList: image_list,
      virtualImageList: virtual_list
    })
  },
  /**
  * 添加商品
  */
  bindUploadShop:function(e){
    var goods = e.currentTarget.dataset.goods;
    wx.navigateTo({
      url: '/packageCommunity/pages/addGoods/index?good='+JSON.stringify(goods),
    })
  },
  /**
   * 删除--添加商品
   */
  onDelShopEvent:function(e){
    var that = this;
    var imgidx = e.currentTarget.dataset.imgidx;
    var image_list = that.data.uploadShopList;
    image_list.splice(imgidx, 1);
    var virtual_list = that.data.shopImageList;
    virtual_list.splice(imgidx, 1);
    that.setData({
      uploadShopList: image_list,
      shopImageList: virtual_list
    })
  },
  /**
   * 文本域 
   */
  changeReaderValue(e){
    let value = e.detail.value;
    this.setData({
      readerValue:value,
      currentNum:value.length
    })
  },
  /**
   * 标题 
   */
  // changeTitle(e){
  //   let value = e.detail.value;
  //   this.setData({
  //     Title:value
  //   })
  // },
  /**
   * 发布
   */
  btnRelease:function(){
    var that = this;
    var imgs = this.data.virtualImageList;
    for(var i=0;i<imgs.length;i++){
      imgs[i] = imgs[i].replace(that.data.imgDomain,'');
    }
    if(this.data.uploadImageList.length == 0){
      util.alert('请添加图片'); 
      return;
    }else if(!this.data.readerValue){
      util.alert('请输入内容');
      return;
    }else if(!this.data.SectionName){ 
      util.alert('请选择板块');
      return; 
    } 
    let data = {Type:this.data.type,Title:'',Image:imgs,Video:'',Content:this.data.readerValue,LinkSrc:'',LinkName:'',SectionId:this.data.SectionId,RelateType:2,SaleType:'',SaleValue:'',ScopeType:0,ScopeValue:'',goods:this.data.uploadShopList};
    // console.log(data,'----data');
    // return;
    comments.getBindPost(data,function(content){
      // console.log(content,'---发布');
      if(content.Success){
        wx.redirectTo({
          url: '/packageCommunity/pages/success/index?id='+content.Content.Id,
        })
      }else{
        util.alert(content.Message);
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let pages = getCurrentPages();
    let currPage = pages[pages.length - 1];
    if (currPage.data.SectionId) {
      this.setData({
        SectionId: this.data.SectionId,
        SectionName:this.data.SectionName
      });
    }
    if(currPage.data.uploadShopList.length>0){
      this.setData({
        uploadShopList:this.data.uploadShopList
      })
    }
    // console.log(this.data.uploadShopList,'-----list');
  },
  navDataList:function(){ 
    var that = this;
    comments.getNavList(function(content){
      let hasGoods = content.Content.filter((item)=>item.Reorder !== -1).filter((item)=>item.Reorder !== -3);
      that.setData({
        navList:hasGoods,
        SectionName:hasGoods[0].Name,
        SectionId:hasGoods[0].Id
      })
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () { 

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})